const ipc = document.querySelector("#ip");
const ipLocation = document.querySelector("#ipLocation");
const ipText = document.querySelector("#iptext");
const osc = document.querySelector("#os");

/*
 * IP文本框事件
 */
ipText.oninvalid = function () {
    this.setCustomValidity(this.validity.valueMissing? "请输入IP地址" : "IP地址错误");
};
ipText.onkeydown = function () {
    this.setCustomValidity('')
};

/**
 * Ajax提交数据
 */
function checkForm() {
    doLookup(ipText.value)
    return false;
}
window._ref="012345789ABCDEFGHIJMNOPRSTVXYZ#$>+*~%";

/**
 * 获取IP归属地
 */
function doLookup(ip) {
    ip = ip || "";
    doAjax("ip/lookup", {ip}, (result) => {
        let data = result.data || {};
        ipc.innerHTML = data.ip;
        ipLocation.innerHTML = data.country + " " + data.area;
        osc.innerHTML = "操作系统 " + data.os;
    });
}

/**
 * 封装Axios Ajax
 * 参数说明：https://axios-http.com/zh/docs/req_config
 */
function doAjax(url, params, callback, method, errCallback) {
    method = (method || "POST").toUpperCase();
    params = params || {};
    errCallback = errCallback || function (){};

    if (url) {
        // Ajax请求参数
        let options = {
            method,
            url,
            headers: {'X-Requested-With': 'XMLHttpRequest'}, // Ajax请求标识
            params
        };
        if ("GET" !== method) {
            options.params = null;
            options.data = params instanceof FormData? params : queryStringify(params);
        }

        // 发起请求
        return axios(options).then((response) => {
            callback && callback(response.data, response);
            return response;
        }).catch((err) => { // Ajax异常处理机制
            console.log("Ajax请求异常：" + err);
            errCallback(err);
        });
    }
}

/**
 * 将对象转换为查询字符串
 * 参数说明：https://github.com/ljharb/qs
 */
function queryStringify(obj, config) {
    if (obj) {
        config = Object.assign({allowDots: true, arrayFormat: 'comma', skipNulls:true}, config || {});
        return Qs.stringify(obj, config);
    }
    return obj;
}

/**
 * 页面加载事件
 */
window.onload = function () {
    doLookup();
};